//页面跳转
import * as URL from 'url-parse';
import * as qs from 'querystringify'
import config from '@/common/js/configTemp'

// export default {
// install:(app, options)=>{
// 	console.log('===install===pageJump===')
// 	const pageJump = (url)=>{
// 		console.log('==pageJump==',url)
// 	};
// 	app.provide('$pageJump',pageJump)
// }
// }

const pageJump = (url) => {
	if (!url) {
		console.warn('pageJump to empty url');
		return false;
	}
	if (url.startsWith('/')) {
		url = 'page:/' + url;
	}
	url = new URL(url, config.BASE_URL, qs.parse);
	let protocol = url.protocol;
	let protoArr = ['http','pages/'];
	let regUrl = protoArr.includes(url)
	if(!regUrl){
		console.error('===pageJump===url is error===url:', url.pathname);
		return false;
	}
	let path = '';
	switch (protocol) {
		case 'http:':
		case 'https:':
			// #ifdef APP-PLUS
			if (url.query['browser']) {
				plus.runtime.openURL(url);
				return true;
			}
			// #endif
			// url.query['plat'] = 1;
			url.query['channelId'] = config.CHANNEL_ID;
			url.query['version'] = config.VERSION;
			let href = `/pages/web/web?url=${encodeURIComponent(url.toString())}`;
			console.log('web-view======>', url.toString());
			uni.navigateTo({
				url: href
			});
			break;
		case 'page:':
			path = '/' + url.hostname + url.pathname;
			if (url.query && Object.keys(url.query).length > 0) {
				path += ('?' + decodeURIComponent(qs.stringify(url.query)));
			}
			uni.navigateTo({
				url: path
			});
			break;
		case 'app:':
			path = url.pathname;
			console.log(path)
			if (url.query && Object.keys(url.query).length > 0) {
				path += ('?' + decodeURIComponent(qs.stringify(url.query)));
			}
			// #ifdef APP-PLUS
			plus.share.getServices(res => {
				let sweixin = null;
				for (let t of res) {
					if (t.id === 'weixin') {
						sweixin = t;
					}
				}
				if (sweixin) {
					sweixin.launchMiniProgram({
						id: url.hostname,
						type: 0,
						path: path,
					});
				}
			}, e => {
				console.error(e);
			});
			// #endif
			// #ifdef MP
			uni.navigateToMiniProgram({
				appId: url.hostname,
				path: path,
			});
			// #endif
			break;
		case 'tab:':
			path = '/' + url.hostname + url.pathname;
			if (url.query && Object.keys(url.query).length > 0) {
				path += ('?' + decodeURIComponent(qs.stringify(url.query)));
			}
			uni.switchTab({
				url: path
			});
			break;
		default:
			console.error('===pageJump===protocol is error', protocol,url);
			break;
	}
}

uni.$pageJump = pageJump;